<?php
/**
 * Answer Service
 * User: zng
 * Date: 2019/11/4
 * Time: 14:34
 */
namespace app\admin\service\questions;

use app\admin\model\questions\Answer as AnswerModels;
use think\Db;

Class Answer {

    /**
     * 首页列表
     * @param array $get 筛选条件
     * @return \think\Paginator
     */
    public function indexPaginate( array $get=[] )
    {
        $map = [];
        $map[] = ['qid', '=', $get['qid']];
        if ( get($get, 'title') ) {
            $map[] = ['title', 'LIKE', '%'.$get['title'].'%'];
        }
        $config = config('field.answer');
        if ( in_array(get($get, 'type'), array_keys($config['type']) ) ) {
            $map[] = [ 'type', '=', $get['type'] ];
        }
        $pageSize = get($get,'pageSize')>0?$get['pageSize']:20;

        return AnswerModels::where($map)
            ->order('id', 'desc')
            ->paginate($pageSize);
    }

    /**
     * 新增优惠券信息
     * @param array $data 数据包
     * @return boolean|integer
     */
    public function create(array $data)
    {
        $answer = AnswerModels::create($data, ['title','type','qid','analysis']);
        return $answer->isEmpty()?false:$answer->id;
    }

    /**
     * 批量删除
     * @param mixed $data
     * @return boolean
     */
    public function destory( $data )
    {
        Db::startTrans();
        if ( is_array( $data ) ) {
            foreach ( $data as $_data ) {
                $opt = AnswerModels::get($_data, 'opt');
                if (false === $opt->together('opt')->delete()) {
                    Db::rollback();
                    return false;
                }
            }
        } else {
            $opt = AnswerModels::get($data, 'opt');
            if (false === $opt->together('opt')->delete()) {
                Db::rollback();
                return false;
            }
        }
        Db::commit();
        return true;
    }

    /**
     * 试题管理编辑
     * @param AnswerModels $model
     * @param array $data
     */
    public function save(AnswerModels $model, array $data)
    {
        $model->title = $data['title'];
        $model->qid = $data['qid'];
        $model->type = $data['type'];
        $model->analysis = $data['analysis'];
        return $model->save();
    }

}